

import type { MockMethod } from "vite-plugin-mock";
import { mock, Random } from "mockjs";

import qs from "qs"
const dataGoods = mock({
  "list|10": [
    {
      goods: () => Random.name(),
      price: 3000,
    },
  ],
});

//用户信息数据
function createUserList() {
  return [
    {
      userId: 1,
      avatar:
        "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
      username: "admin",
      pwd: "admin",
      desc: "平台管理员",
      roles: ["平台管理员"],
      buttons: ["cuser.detail"],
      routes: ["home"],
      token: "Admin Token",
    },
    {
      userId: 2,
      avatar:
        "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
      username: "system",
      pwd: "111111",
      desc: "系统管理员",
      roles: ["系统管理员"],
      buttons: ["cuser.detail", "cuser.user"],
      routes: ["home"],
      token: "System Token",
    },
  ];
}
function getUrlParam(name, paramStr) {
 
    const  reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"),
      r = paramStr.match(reg);
  return r != null ? decodeURI(r[2]) : "";
};

export default [
  // 用户登录接口
  {
    url: "/mock/user/login", //请求地址
    method: "post", //请求方式
    response: (Obj) => {
      //获取请求体携带过来的用户名与密码
      const { body } = Obj
      const {username, pwd} =   qs.parse(body) 
      // let username = '', pwd = ''
      // if (typeof body == 'string') {
     
      //   // username = getUrlParam('username',body)
      //   // pwd = getUrlParam('pwd',body)
      // }
   //   else { username, pwd } = body;
      //调用获取用户信息函数,用于判断是否有此用户
      debugger
      console.log(body)
      const checkUser = createUserList().find(
        (item) => item.username === username && item.pwd === pwd,
      );
      //没有用户返回失败信息
      if (!checkUser) {
        return { code: 201, data: { message: "账号或者密码不正确" } };
      }
      //如果有返回成功信息
      const { token } = checkUser;

      return { code: 200, data: { body } };
    },
  },
  // 获取用户信息
  {
    url: "/mock/user/info",
    method: "get",
    response: (request) => {
      //获取请求头携带token
      debugger
      const token = request.headers.token;
      //查看用户信息是否包含有次token用户
      const checkUser = createUserList().find((item) => item.token === token);
      //没有返回失败的信息
      if (!checkUser) {
        return { code: 201, data: { message: "获取用户信息失败" } };
      }
      //如果有返回成功信息
      return { code: 200, data: { checkUser } };
    },
  },
  {
    url: "/mock/user/list",
    method: "get",
    response: (request) => {
      
      //如果有返回成功信息
      return { code: 200, data: { userlist: createUserList() } };
    },
  },

] as MockMethod[];